using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;

namespace CodeProject.XmlDSigLic
{
	/// <summary>
	/// Console application to sign an XML file.
	/// </summary>
	class Sign
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static int Main(string[] args)
		{
            //Public key
            string keyPairInfo = @"<RSAKeyValue><Modulus>kuETOBjEbkv3081ppnZFgzdRvP32mxC3KfUUwiUBA2BrQG0thv24g8Xd60a0AQkOTV99MMQrrZU2pQxFhfcxzyC0dxcNRf49j7I2KbuFEjhCnlRas4U+Zq8MkNIgkB9yXUknsPl025dEkT9GEtaZxH/LJDTaav1yHneUgQYl2sU=</Modulus><Exponent>AQAB</Exponent><P>vZhMAZn3UjuHpIl4NAvgAhd+mj2W38JF4+m3MsupO0nzat+MD1lZmnl7/xc5j7ILn7496zttBcjxZ6EkegC6QQ==</P><Q>xlK/Q1tIYFCepC4LD9nZfUmi4uMXm2kyhGMGnmV1uUej0S4yObhsOo9oebqyaLaQzkJ8fKZRYUFcXs667DlXhQ==</Q><DP>LlkNs5KE8FhXJ3TnqqmAgGJn86K8wESIu1eGDmfVHgZM+EJfxdzM18N8+XYe/y7CQrHKBzhGxZRC11eASEbnQQ==</DP><DQ>Gi6aaX4HlA+QogQiGbmc6Nlr06A/YZkFvkyEdyzV2dwHWHpMzyn1v9Vm6YsoOoK/oztLy/j5DWnfk/Se4MjBMQ==</DQ><InverseQ>XoVqYNMJs2D6u4itMRNLJ4zQ0Y9VULKfumuEZ5FwPpZrbWFoXkH63g38Y7ry6ZhYLbqq7kfGH9aAfKnJZtVlPg==</InverseQ><D>AGl1Yj7k3ugJizzRM81dsFqey05tU5b2sqTznG3hkYNVDLkEtxlaHyFxy8yoTJYolRAdZ0vljiGN9Rv5/Mx8f3aPxwMpjPHTsGm2MKcMeaYVw2999KSFERKWrZ5Y9TE/4Ug6B4wIPii2ooO0W4CxXaZC7xKOMYSVJA12kNaf5AE=</D></RSAKeyValue>";

			// Verify that an XML document path is provided.
            //if (args.Length != 1 || !File.Exists(args[0]))
            //{
            //    Console.Error.WriteLine("Error: You must provide the path to an XML " +
            //        "document to sign.");
            //    return 1;
            //}

			// Load the license request file.
			XmlDocument xmldoc = new XmlDocument();
            //xmldoc.Load(args[0]);
            string xmlFileName = @"d:\samplexml.xml";
            xmldoc.Load(xmlFileName);

			// Get the key pair from the key store.
            //CspParameters parms = new CspParameters(1);			// PROV_RSA_FULL
            //parms.Flags = CspProviderFlags.UseMachineKeyStore;	// Use Machine store
            //parms.KeyContainerName = "CodeProject";				// "CodeProject" container
            //parms.KeyNumber = 2;								// AT_SIGNATURE
			RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
            csp.FromXmlString(keyPairInfo);

			// Creating the XML signing object.
			SignedXml sxml = new SignedXml(xmldoc);
			sxml.SigningKey = csp;

			// Set the canonicalization method for the document.
			sxml.SignedInfo.CanonicalizationMethod = 
				SignedXml.XmlDsigCanonicalizationUrl; // No comments.

			// Create an empty reference (not enveloped) for the XPath
			// transformation.
			Reference r = new Reference("");

			// Create the XPath transform and add it to the reference list.
			r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));

			// Add the reference to the SignedXml object.
			sxml.AddReference(r);

			// Compute the signature.
			sxml.ComputeSignature();

			// Get the signature XML and add it to the document element.
			XmlElement sig = sxml.GetXml();
			xmldoc.DocumentElement.AppendChild(sig);

			// Write-out formatted signed XML to console (allow for redirection).
            XmlTextWriter writer = new XmlTextWriter(xmlFileName, null);
			writer.Formatting = Formatting.Indented;

			try
			{
				xmldoc.WriteTo(writer);
			}
			finally
			{
				writer.Flush();
				writer.Close();
			}
            

			return 0;
		}
	}
}
